package com.gitee.loyo.interfaces

import java.lang.StringBuilder

interface NameMappingStrategy {
    fun toColumnName(fieldName: String): String
    fun toFieldName(columnName: String): String

    companion object {
        val UNDERSCORE: NameMappingStrategy = object : NameMappingStrategy {
            override fun toColumnName(fieldName: String): String {
                val builder = StringBuilder(fieldName.length)
                var c: Char
                for (i in fieldName.indices) {
                    c = fieldName[i]
                    if (Character.isUpperCase(c) && i > 0) {
                        builder.append('_').append(Character.toLowerCase(c))
                    } else {
                        builder.append(Character.toLowerCase(c))
                    }
                }
                return builder.toString()
            }

            override fun toFieldName(columnName: String): String {
                val builder = StringBuilder(columnName.length)
                var underline = false
                for (c in columnName) {
                    if ('_' == c) {
                        underline = true
                        continue
                    }
                    if (underline) {
                        underline = false
                        builder.append(Character.toUpperCase(c))
                    } else {
                        builder.append(Character.toLowerCase(c))
                    }
                }
                return builder.toString()
            }
        }
    }
}